<?php
namespace Api\Controller;
use Think\Controller;
class IndexController extends CommonController {

    public $ToUserName;
    public $FromUserName;
    public $MsgType;
    public $postObj;
    public function index(){

    	if(isset($_GET['echostr'])){
    		 $echoStr = $_GET["echostr"];
		    //valid signature , option
	        if($this->checkSignature()){
	        	echo $echoStr;
	        	exit;
	        }
    	}else{
    		$this->respones();
    	}

       
    }

    public function viewlog()
    {
    	var_dump(M('log')->order("ctime desc")->select());
    }

    public function respones()
    {

    	$this->log(['info'=>$GLOBALS['HTTP_RAW_POST_DATA']]);

        //获取原始xml格式的数据
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];

        //转成对象
        $this->postObj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);

        $this->ToUserName = $this->postObj->ToUserName;

        $this->FromUserName = $this->postObj->FromUserName;

        $this->MsgType = $this->postObj->MsgType;

        $this->dealData();

        file_put_contents('./db.txt',  $data);
    }

    public function dealData()
    {
        switch ($this->MsgType) {
            case 'text':
                $this->text();
                break;
            case 'image':
                $this->images();
                break;
            case 'voice':
                $this->voice();
                break;

            case "event":
                $this->event();
                break;
            default:
                $this->default();
                break;
        }
    }

    public function event()
    {
        $Event = $this->postObj->Event;

        if($Event=='subscribe'){
            $str = "<xml>
<ToUserName><![CDATA[".$this->FromUserName."]]></ToUserName>
<FromUserName><![CDATA[".$this->ToUserName."]]></FromUserName>
<CreateTime>".time()."</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[欢迎关注XXX的我们！！！！]]></Content>
</xml>";
        echo $str;
        }
    }

    public function text()
    {
        $text = $this->postObj->Content;

        if($text=="新闻"){
            $this->return_news();
        }

        $res = robots($text);

        $str = "<xml>
<ToUserName><![CDATA[".$this->FromUserName."]]></ToUserName>
<FromUserName><![CDATA[".$this->ToUserName."]]></FromUserName>
<CreateTime>".time()."</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[".$res['values']['text']."]]></Content>
</xml>";
        echo $str;
    }

    public function return_news()
    {
        $data = array(
            array(
                'title'=>"百度在一边哭",
                'description'=>"这样好吗",
                'picurl'=>"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png",
                'url'=>'http://www.baidu.com'
                ),
            array(
                'title'=>"新浪",
                'description'=>"新浪吗",
                'picurl'=>"http://i2.sinaimg.cn/dy/deco/2013/0329/logo/LOGO_2x.png",
                'url'=>'http://www.sina.com'
                )
            );
        $str = "<xml>
<ToUserName><![CDATA[".$this->FromUserName."]]></ToUserName>
<FromUserName><![CDATA[".$this->ToUserName."]]></FromUserName>
<CreateTime>".time()."</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>".count($data)."</ArticleCount>
<Articles>";

    foreach ($data as $row) {
        $str.="<item>
<Title><![CDATA[".$row['title']."]]></Title> 
<Description><![CDATA[".$row['description']."]]></Description>
<PicUrl><![CDATA[".$row['picurl']."]]></PicUrl>
<Url><![CDATA[".$row['url']."]]></Url>
</item>";

    }

    $str .="</Articles></xml>";

    echo $str;


    }

    public function images()
    {
        $PicUrl = $this->postObj->PicUrl;
        $MediaId = $this->postObj->MediaId;
        // $this->log(['info'=>$PicUrl]);
        $str="<xml>
<ToUserName><![CDATA[".$this->FromUserName."]]></ToUserName>
<FromUserName><![CDATA[".$this->ToUserName."]]></FromUserName>
<CreateTime>".time()."</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[".$MediaId."]]></MediaId>
</Image>
</xml>";
    echo $str;

    }

    public function voice()
    {
        $MediaId = $this->postObj->MediaId;
        $this->log(['info'=>$MediaId]);

    }

    public function checkSignature()
    {
    	// you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
    }
}